package com.edu.internship.busi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.internship.busi.dto.StudentDTO;
import com.edu.internship.busi.entity.Student;
import com.edu.internship.busi.service.IStudentService;
import org.apache.tools.ant.util.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
/**
 * code is far away from bug with the animal protecting
 *
 * @author longjihao
 * @description <p>Student 的controller</p>
 * @date 2020-08-02
 */
@RestController
@Slf4j
@RequestMapping("/student")
@Api(tags = {"学生项的控制器"})
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @GetMapping("All")
    @ApiOperation(value = "分页查询-Student", notes = "根据条件进行查询-Student")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页数", dataTypeClass = Long.class, paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页几条记录", dataTypeClass = Long.class, paramType = "query", defaultValue = "10")
    })
    public IPage<Student> page(StudentDTO dto, @RequestParam(defaultValue = "1") Long current,
                               @RequestParam(defaultValue = "5") Long size) {
        LambdaQueryWrapper<Student> dictionaryQw = Wrappers.lambdaQuery();
        dictionaryQw.like(StringUtils.isNotBlank(dto.getStudentName()), Student::getStudentName, dto.getStudentName())
                .like(StringUtils.isNotBlank(dto.getClassId()), Student::getClassId, dto.getClassId())
                .like(StringUtils.isNotBlank(dto.getStudentSex()), Student::getStudentSex, dto.getStudentSex())
                .like(StringUtils.isNotBlank(dto.getStudentNumber()), Student::getStudentNumber, dto.getStudentNumber());
        return studentService.page(new Page<>(current, size), dictionaryQw);
    }

    @GetMapping("/getById")
    @ApiOperation(value = "获取信息id-Student",notes = "获取信息id-Student")
    public List<Student> getById(StudentDTO dto) {
        LambdaQueryWrapper<Student> studentQw = Wrappers.lambdaQuery();
        studentQw.eq(Student::getId, dto.getId());
        return studentService.list(studentQw);
    }

    @PostMapping("create")
    @ApiOperation(value = "新增-Student", notes = "新增-Student")
    public void save(@RequestBody StudentDTO dto){
        studentService.createStudent(dto);
    }

    @PostMapping("update")
    @ApiOperation(value = "更新-Student", notes = "更新-Student")
    public void update(@RequestBody StudentDTO dto){
        studentService.updateStudent(dto);
    }

    @PostMapping("remove")
    @ApiOperation(value = "删除-Student", notes = "删除-Student")
    public void delete(@RequestBody List<String> id){
        studentService.removeStudent(id);
    }

    @GetMapping
    @ApiOperation(value = "查询-Student", notes = "根据条件进行查询-Student")
    public List<Student> list(StudentDTO dto) {
        LambdaQueryWrapper<Student> studentQw = Wrappers.lambdaQuery();
        studentQw.eq(Student::getId, dto.getId())
                .like(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(dto.getStudentName()), Student::getStudentName, dto.getStudentName())
                .like(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(dto.getStudentNumber()), Student::getStudentNumber, dto.getStudentNumber())
                .like(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(dto.getClassId()), Student::getClassId, dto.getClassId());
        return  studentService.list(studentQw);
    }


    @GetMapping("/reportExport/prodTest")
    @ApiOperation(value = "导出excel文件", notes = "导出excel文件")
    public Object prodTest(HttpServletResponse response, String excelTitle) throws IOException {
        // 创建导出文件名称 当前日期+前台传递过来的标题名（excelTitle）
        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss") +"-"+excelTitle+".xls";
        // 设置返回的消息头和返回值类型 并设置编码 不设置编码文件名为中文的话 不会显示
        // 当设置成如下返回值时，浏览器才会执行下载文件动作
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        // 创建输出流，调用service中exportTest方法，参数：输出流 标题名
        studentService.exportTest(response, excelTitle);
        return null;
    }

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation(value = "导入excel文件", notes = "导入excel文件")
    public String excelImport(@RequestParam(value = "filename") MultipartFile file, HttpSession session){
        String fileName = file.getOriginalFilename();
        int result = 0;

        try {
            result = studentService.addStudentExcelFileToDatabase(file);
        } catch (Exception e){
            e.printStackTrace();
        }

        if (result > 0){
            return "导入成功！";
        }else {
            return "导入失败了...";
        }
    }


}
